/*
 * @Author: aggfb 714740235@qq.com
 * @Date: 2024-10-01 10:22:46
 * @LastEditors: aggfb 714740235@qq.com
 * @LastEditTime: 2024-10-13 17:40:52
 * @FilePath: \baking_machine\bsp\bap_timer.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "motor.h"
#include "bsp_uart.h"
#include <stdio.h>
#include <string.h>

/**
 * 通过adc的值,计算相电流
 */
float phase_current_from_adcval(uint16_t adc_val) 
{
    int adcval_bal = (int)(adc_val - (1 << 11));
    // 得到采样电阻上的电压
    float amp_out_volt = (ADC_FULLSCALE_VOLT / (float)ADC_FULL_BIT) * (float)adcval_bal;
    float shunt_volt = amp_out_volt * SHUNT_OPA_GAIN; // 分流电压
    float current = shunt_volt / SHUNT_RES;
    return current;
}

/**
 * 相电流校准
 */
uint8_t motor_phase_current_calibration(motor_t* motor, uint16_t adc_val)
{
    motor->cali_sum += phase_current_from_adcval(adc_val); 
    if(++motor->iphase_cali_times >= LOW_LEVEL_CURRENT_CALI_TIMES)
    {
        motor->iphase_offset = motor->cali_sum / motor->iphase_cali_times;
        motor->is_iphase_cali = true;
        motor->cali_sum = 0;
        return 1;
    }
    return 0;
}

/**
 * 将计算后的PWM值,更新到执行寄存器
 */
void motor_apply_pwm_timings(motor_t* motor; uint16_t timings[3]) 
{
    if(motor->enable_pwm_out == 0)
    {
        TIMER_CH0CV(motor->timer) = (uint16_t)timings[0];
        TIMER_CH1CV(motor->timer) = (uint16_t)timings[1];
        TIMER_CH2CV(motor->timer) = (uint16_t)timings[2];        
    }
    else
    {
        timer_disable(motor->timer);
    }
}